package com.jqb.jsplab.dao.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.jqb.jsplab.dao.ITestDao;
import com.jqb.jsplab.util.FileUploadTool;
import com.jspsmart.upload.SmartUpload;

public class TestDaoImpl implements ITestDao {
	
	/**
	 * 传统方式文件上传
	 * */
	@Override
	public boolean fileUpload(HttpServletRequest request, HttpServletResponse response) {
		/**
		 * 1.创建磁盘工厂DiskFileItemFactory
		 */
		DiskFileItemFactory factory = new DiskFileItemFactory();
		/**
		 * 1.1设置缓存目录
		 */
		String uploadtmpdir = request.getSession().getServletContext().getRealPath("/")	+ "/useruploadtmp";
		factory.setRepository(new File(uploadtmpdir));
		/**
		 * 1.2设置缓存大小
		 */
		factory.setSizeThreshold(1024 * 1024);
		/**
		 * 2.创建处理类ServletFileUpload
		 */
		ServletFileUpload upload = new ServletFileUpload(factory);
		/**
		 * 2.1设置长传文件大小
		 */
		upload.setFileSizeMax(3 * 1024 * 1024);
		/**
		 * 设置存放上传文件的目录
		 */
		String uploaddir = request.getSession().getServletContext().getRealPath("/") + "/userupload";
		try {
			/**
			 * 2.2解析HttpServletRequest,获取所有内容
			 */
			List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
			/**
			 * 便利方法
			 */
			for (FileItem item : items) {
				/**
				 * 获取字段名称
				 */
				String name = item.getFieldName();

				/**
				 * 判断是否是普通字段
				 */
				if (item.isFormField()) {
					String value = item.getString();
					request.setAttribute(name, value);
					System.out.println(name + "=" + value);
				} else {
					/*文件*/
					/**
					 * 获取上传文件名并解决中文名
					 */
					String value = new String(item.getName().getBytes(),"UTF-8");
					/**
					 * 获取正真的上传文件名(有的浏览器会带有路径:X:\\xxx\\file.txt)
					 */
					String fileName = value.substring(value.lastIndexOf("\\") + 1);
					if ((fileName != null) && (!fileName.equals(""))) {
						request.setAttribute(name, fileName);
						item.write(new File(uploaddir, fileName));
						System.out.println(name + "=" + fileName);
					}
				}
			}
			return true;
		} catch (Exception e) {
			System.out.println("...uploading failed...");
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 使用SmartUpload组件上传文件
	 */
	@Override
	public boolean smartFileUpload(Servlet servlet, HttpServletRequest request,HttpServletResponse response) {
		/**
		 * 初始化SmartUpload
		 */
		SmartUpload su = new SmartUpload();
		PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(servlet, request, response, "", true, 8192, true);
		/**
		 * 存放图片信息和文字描述
		 */
		List<String> pics = new ArrayList<String>();
		List<String> describes = new ArrayList<String>();
		try {
			su.initialize(pageContext);
			su.upload();
			int count = su.getFiles().getCount();
			if (count != 0) {
				String fileName;
				for (int i = 0; i < count; i++) {
					fileName = su.getFiles().getFile(i).getFileName();
					/**
					 * 通过正则限制上传文件必须是JPG或GIF
					 */
					if (fileName == null || !fileName.matches("^\\S+\\.(jpg|gif)$")) {
						return false;
					}
				}
				for (int i = 0; i < count; i++) {
					fileName = su.getFiles().getFile(i).getFileName();

					/**
					 * 保存信息
					 */
					pics.add(fileName);
					String describe = su.getRequest().getParameter("describe" + i);
					describes.add(describe);

					/**
					 * 文件上传
					 */
					su.getFiles().getFile(i).saveAs(request.getSession().getServletContext().getRealPath("/") + "/userupload" + File.separator + fileName);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		request.setAttribute("pics", pics);
		request.setAttribute("describes", describes);
		return true;
	}

	/**
	 * 使用SmartUpload组件下载文件
	 */
	@Override
	public boolean smartFileDownload(Servlet servlet,HttpServletRequest request, HttpServletResponse response,String filename) {
		/**
		 * 初始化SmartUpload
		 */
		SmartUpload su = new SmartUpload();
		PageContext pagecontext = JspFactory.getDefaultFactory().getPageContext(servlet, request, response, "", true, 8192,	true);
		try {
			su.initialize(pagecontext);
			su.setContentDisposition(null);
			/**
			 * 下载文件
			 */
			su.downloadFile("/userupload/" + filename);

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 多文件上传
	 * */
	@Override
	public boolean multiFileUpload(HttpServletRequest request, HttpServletResponse response) {
		/**
		 * 临时目录和存盘目录
		 */
		String tmpDir = request.getSession().getServletContext().getRealPath("/") + "/useruploadtmp";
		String saveDir = request.getSession().getServletContext().getRealPath("/") + "/userupload";

		try {
			/**
			 * 获取封装过的工具对象
			 */
			FileUploadTool fut = new FileUploadTool(request, 3 * 1024 * 1024, tmpDir);

			/**
			 * 获取普通字段值
			 */
			String name = fut.getParameter("username");
			String[] interests = fut.getParameterValues("interest");
			/**
			 * 保存文件到存盘目录
			 */
			List<String> allFiles = fut.saveAll(saveDir + File.separator);

			if (name != null) {
				request.setAttribute("name", name);
			}
			if (interests != null) {
				request.setAttribute("interests", interests);
			}
			if (allFiles != null) {
				request.setAttribute("allFiles", allFiles);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 简易聊天
	 * */
	@Override
	public void showMessage(HttpServletRequest request, HttpServletResponse response) {
		String newwords = null;
		String oldwords = null;
		newwords = request.getParameter("words");
		oldwords = (String) request.getSession().getServletContext().getAttribute("msg");
		if (oldwords == null) {
			oldwords = "welcome";
		}
		if (newwords != null) {
			oldwords = oldwords + "\n" + newwords;
		}
		System.out.println(newwords + "--" + oldwords);
		request.getSession().getServletContext().setAttribute("msg", oldwords);
	}
	/**
	 * 迭代标签
	 * */
	@Override
	public void showTagList(HttpServletRequest request, HttpServletResponse response) {
		List<String> infos = new ArrayList<String>();
		String nickname = null;
		String email = null;
		String[] interests = null;
		nickname = request.getParameter("nickname");
		email = request.getParameter("email");
		interests = request.getParameterValues("interest");
		infos.add(nickname);
		infos.add(email);
		for (String i : interests) {
			infos.add(i);
		}
		request.setAttribute("list", infos);
	}
	/**
	 * 字符串排序
	 */
	@Override
	public void sortString(HttpServletRequest request,HttpServletResponse response) {
		String words = request.getParameter("words");
		String sortkind = request.getParameter("sortkind");
		/**
		 * 通过正则表达式分割字符串(逗号或空格)
		 */	
		String regex = "" + ',' + "|" + ' ' + "";
		//可以对String数组排序因为String实现了Comparable接口,但是如果有负数就不行了
		String[] word = words.split(regex);
		int[] nums = new int[word.length];
		for (int i = 0; i < word.length; i++) {
			nums[i]=Integer.parseInt(word[i]);
		}
		/**
		 * 升序/降序
		 */
		if ("asc".equals(sortkind)) {
			Arrays.sort(nums);
		}
		if("dec".equals(sortkind)){
			Arrays.sort(nums);
			for (int i = 0; i < nums.length / 2; i++) {
				int tmp = nums[i];
				nums[i] = nums[nums.length - i - 1];
				nums[nums.length - i - 1] = tmp;
			}
		}
		request.setAttribute("sortedResult", Arrays.toString(nums));
	}

}
